<script setup>
import { ref, onMounted } from 'vue'
import easyapi from '../api'
import { ElMessage, ElMessageBox, pageHeaderEmits } from 'element-plus'
//定义绑定的数据
const tableData = ref([]);
//控制新增信息窗口是否显示
const addWinVisible = ref(false);
//新增数据绑定对象
const addObject = ref({});
//控制新增信息窗口是否显示
const editWinVisible = ref(false);
//编辑数据绑定对象
const editObject = ref({});
//记录编辑数据的下标
var editIndex = -1;
//分页的总页数
const total = ref(100)
//查询数据输入框的绑定对象
const checkObj = ref({
    size: 3,
    page: 1
})


onMounted(async function () {
    await checkData();
})

//删除数据
const del = function (index, row) {
    ElMessageBox.confirm(
        '确认删除该行数据吗?',
        '警告',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(async () => {
            //提交数据
            await easyapi.del('/api/user', row.id)
            //刷新表单数据
            tableData.value.splice(index, 1)
            if (tableData.value.length == 0) {
                checkObj.value.page = (checkObj.value.page - 1) < 1 ? 1 : checkObj.value.page - 1;
                checkData(checkObj.value.page)
            } else {
                checkData(checkObj.value.page)
            }
            //提示删除成功
            ElMessage({
                type: 'success',
                message: '删除成功',
            })
        })
        .catch(() => {
            ElMessage({
                type: 'info',
                message: '取消删除',
            })
        })
}

//新增数据
//显示新增窗口
const openAddWin = async function () {
    addObject.value = {}
    imageUrl.value = 'api' + '/img/default.png'
    addWinVisible.value = true;
}
//关闭新增窗口
const closeAddWin = function () {
    addWinVisible.value = false;
}

//头像
const imageUrl = ref({})

const handleAvatarSuccess = (response, uploadfile) => {
    imageUrl.value = 'api' + response.data
    addObject.value.imgUrl = response.data
    editObject.value.imgUrl = response.data
}


//上次新增数据
const addSave = async function () {
    addForm.value.validate(async (valid) => {
        if (valid) {
            //保存新增的数据 addObject
            //发送请求
            let result = await easyapi.postJson('/api/user', addObject.value);
            //当前页行数小于size则将数据添加到该页
            if (tableData.value.length < checkObj.value.size) {
                tableData.value.push(result.data);
            } else {
                checkData();
            }
            //刷新表单
            //提示新增成功
            ElMessage({
                type: 'success',
                message: '新增数据成功',
            })
            //关闭窗口
            closeAddWin()
        } else {
            ElMessage({
                type: 'info',
                message: '格式错误',
            })
        }
    })
}

//修改数据
//显示编辑窗口
const openEditWin = function () {
    editWinVisible.value = true;
}
//关闭编辑窗口
const closeEditWin = function () {
    editWinVisible.value = false;
}
//点击编辑按钮，执行的方法
const edit = function (index, row) {
    //绑定要修改的数据
    editObject.value.id = row.id
    imageUrl.value = 'api' + row.imgUrl
    editObject.value.imgUrl = row.imgUrl
    editObject.value.username = row.username;
    editObject.value.phoneNumber = row.phoneNumber;
    editObject.value.oldPassword = ''
    editObject.value.password = ''
    editIndex = index;
    //打开对话框
    openEditWin();
}
//保存修改编辑数据
const editSave = async () => {

    editForm.value.validate(async (valid) => {
        if (valid) {
            //发送请求
            let result = await easyapi.putJson('/api/user', editObject.value)
            //刷新表单
            tableData.value[editIndex] = result.data;
            //提示
            ElMessage({
                type: 'success',
                message: '编辑数据成功',
            })
            result = await easyapi.get('/api/decodetoken')
            let id = result.data.id
            if(id === editObject.value.id){
                location.reload()
            }
            //关闭窗口
            closeEditWin()
        } else {
            ElMessage({
                type: 'info',
                message: '格式错误',
            })
        }
    })
}

//查询功能
const checkData = async (val) => {
    //获取当前页数
    if (typeof val == 'number') {
        checkObj.value.page = val;
    }
    //查询数据
    let result = await easyapi.getSearch('/api/user', checkObj.value)
    //更新表格中的数据
    tableData.value = result.data.list;
    total.value = result.data.count;
}

const getFullImageUrl = (relativeUrl) => {

    return `/api${relativeUrl}`;
}


const tableRowStyle = (row) => {
    return row.rowIndex % 2 === 0 ?
        { background: 'white' } :
        { background: '#FFF0F5' };
};

//表单验证
const addForm = ref({})

const addCheckRules = {
    username: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    phoneNumber: [
        { required: true, message: '请输入电话号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: /^.{6,16}$/, message: '密码长度在6-16之间', trigger: 'blur' }
    ]
}

const editForm = ref({})

const checkOldPassword = async (rule, value, callback) => {
    let result = await easyapi.getSearch("api/checkOldPassword",editObject.value)
    if (result.code == 200) {
        callback();
    } else {
        callback(new Error('原密码错误'))
    }
}

const checkNewPassword = async (rule, value, callback) => {
    if (editObject.value.password == editObject.value.newPassword) {
        callback();
    } else {
        callback(new Error('两次密码不一致'))
    }
}



const editCheckRules = {
    username: [
        { required: true, message: '请输入姓名', trigger: 'blur' },
    ],
    phoneNumber: [
        { required: true, message: '请输入电话号码', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { pattern: /^.{6,16}$/, message: '密码长度在6-16之间', trigger: 'blur' }
    ],
    oldPassword: [
        { required: true, message: '请输入旧密码', trigger: 'blur' },
        { pattern: /^.{6,16}$/, message: '密码长度在6-16之间', trigger: 'blur' },
        { validator: checkOldPassword, trigger: 'blur' }
    ],
    newPassword: [
        { required: true, message: '请确认新密码', trigger: 'blur' },
        { validator: checkNewPassword, trigger: 'blur' }
    ]
}
</script>
<template>
    <el-input v-model="checkObj.username" style="width: 150px" placeholder="请输入查询的姓名" />
    <el-input v-model="checkObj.phoneNumber" style="width: 150px" placeholder="请输入查询的手机号" />
    <el-button type="primary" @click="checkData">查询</el-button>
    <el-button type="primary" @click="openAddWin">新增</el-button>
    <el-table :data="tableData" :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }"
        style="width: 100%" :row-style="tableRowStyle" border>
        <el-table-column prop="imgUrl" label="头像" width="60px">
            <template v-slot="scope">
                <img :src="getFullImageUrl(scope.row.imgUrl)" style="width: 50px; height: 50px; object-fit: cover;">
            </template>
        </el-table-column>
        <el-table-column prop="username" label="管理员姓名" />
        <el-table-column prop="phoneNumber" label="电话号码" />
        <el-table-column label="操作" width="180px" header-align="center">
            <template #default="scope">
                <el-button type="danger" @click="del(scope.$index, scope.row)">删除</el-button>
                <el-button type="success" @click="edit(scope.$index, scope.row)">编辑</el-button>
            </template>
        </el-table-column>
    </el-table>
    <!-- 分页组件初始显示的页码 -->
    <!-- size:每页的条数 -->
    <el-pagination :page-size="checkObj.size" :current-page="checkObj.page" background layout="prev, pager, next"
        :total="total" @current-change="checkData" />


    <!--start 新增信息的弹出框 -->
    <el-dialog v-model="addWinVisible" title="新增管理员" width="500">
        <el-form :model="addObject" :rules="addCheckRules" ref="addForm">
            <el-form-item label="头像" :label-width="80" prop="imgUrl">
                <el-upload class="avatar-uploader" action="api/img" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <img v-if="imageUrl" :src="imageUrl" style="font-size: 28px;color: #8c939d;width: 178px;height: 178px;text-align: center;" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="姓名" :label-width="80" prop="username">
                <el-input v-model="addObject.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电话号码" :label-width="80" prop="phoneNumber">
                <el-input v-model="addObject.phoneNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="密码" :label-width="80" prop="password">
                <el-input v-model="addObject.password" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeAddWin">取消</el-button>
                <el-button type="primary" @click="addSave">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!--end 新增信息的弹出框 -->

    <!--start 修改信息的弹出框 -->
    <el-dialog v-model="editWinVisible" title="修改管理员数据" width="500">
        <el-form :model="editObject" :rules="editCheckRules" ref="editForm">
            <el-form-item label="头像" :label-width="100" prop="imgUrl">
                <el-upload class="avatar-uploader" action="api/img" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <img v-if="imageUrl" :src="imageUrl" style="font-size: 28px;color: #8c939d;width: 178px;height: 178px;text-align: center;" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="姓名" :label-width="100" prop="username">
                <el-input v-model="editObject.username" autocomplete="off" />
            </el-form-item>
            <el-form-item label="电话号码" :label-width="100" prop="phoneNumber">
                <el-input v-model="editObject.phoneNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="旧密码" :label-width="100" prop="oldPassword">
                <el-input v-model="editObject.oldPassword" autocomplete="off" />
            </el-form-item>
            <el-form-item label="新密码" :label-width="100" prop="password">
                <el-input v-model="editObject.password" autocomplete="off" />
            </el-form-item>
            <el-form-item label="确认新密码" :label-width="100" prop="newPassword">
                <el-input v-model="editObject.newPassword" autocomplete="off" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="closeEditWin">取消</el-button>
                <el-button type="primary" @click="editSave">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
    <!--end 修改信息的弹出框 -->

</template>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}
</style>